package com.fante.dubbo.manage.shiro;

import com.fante.dubbo.manage.constant.CommonConstant;
import com.fante.dubbo.manage.entity.SysAdmin;
import com.fante.dubbo.manage.service.SysAdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * 自定义的Realm的认证规则
 * @Author liubao
 * @Date 2020/6/6
 */
public class MyShiroRealm extends AuthorizingRealm {

    private static final transient Logger log = LoggerFactory.getLogger(MyShiroRealm.class);

    @Autowired
    private SysAdminService sysAdminService;
    /**
     * 用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)principalCollection.getPrimaryPrincipal();
        SysAdmin sysAdmin = sysAdminService.findByUserName(username);
        if(sysAdmin == null) {
            return null;
        }
        SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();
        // 设置用户拥有的角色集合
        Set<String> roleSet = sysAdminService.selectRoleS(username);
        simpleAuthenticationInfo.setRoles(roleSet);
        // 设置用户的拥有的权限集合
        Set<String> authoritySet = sysAdminService.selectAuthorityS(username);
        simpleAuthenticationInfo.addStringPermissions(authoritySet);
        return simpleAuthenticationInfo;
    }

    /**
     * 身份认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getCredentials();
        SysAdmin sysAdmin = sysAdminService.findByUserName(username);
        if(sysAdmin == null) {
            throw new AccountException("账户异常");
        } else if(sysAdmin.getIsLocked() ==1) {
            throw new LockedAccountException("账户被锁定");
        }

        //保存登录用户ID
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute(CommonConstant.SUPER_ADMIN, sysAdmin.getUsername());
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                sysAdmin, sysAdmin.getPassword(),getName());

        return simpleAuthenticationInfo;
    }

    /**
     *  清除当前用户的权限缓存
     * @param principals 权限信息
     */
    @Override
    protected void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }
}
